import { getToken, removeToken, setToken } from '@/utils/auth'
import { getInfo, getMoreInfo, login } from '@/api/user'
import { resetRouter } from '@/router'
const state = () => {
  return {
    token: getToken(),
    userInfo: {}
  }
}
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  }
}
const actions = {
  async login(context, data) {
    const token = await login(data)
    setToken(token)
    context.commit('setToken', token)
  },
  async getUserInfo(context) {
    const res = await getInfo()
    const moreRest = await getMoreInfo({ id: res.userId })
    context.commit('setUserInfo', { ...res, ...moreRest })
  },
  logout(context) {
    removeToken()
    context.commit('setToken', undefined)
    context.commit('setUserInfo', {})
    resetRouter()
    context.commit('permission/setRoutes', [], { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
